# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

import datetime

#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    http://..../[app]/default/user/manage_users (requires membership in
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())

@cache.action()
def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request, db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id]
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs must be signed, i.e. db.amicizieed with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())

def index():    
    if not auth.is_logged_in():    
        for field in ["peso", "picture", "sesso_id", "data_nascita"]:        
            db.auth_user[field].readable = db.auth_user[field].writable = False        
        login_form = auth.login()
        register_form = auth.register()
        register_form[0][-3][2] = ""
    else:
        redirect(URL('home'))        
    return locals()

@auth.requires_login()
def home():    
    form = crud.create(db.posts)
    form.custom.widget["corpo"].update(_placeholder=T("A cosa stai pensando?"))    
    comment_form = SQLFORM(db.post_comments, submit_button=T("Commenta"))
    comment_form.custom.widget["corpo"].update(_placeholder=T("Scrivi un commento"))        
    friends = [auth.user_id]+getUserFriends()
    posts = db(db.posts.posted_to.belongs(friends)).select(orderby=~db.posts.data_ora,
                                                              limitby=(0, 100))
    return locals()

@auth.requires_login()
def wall():
    auth_user_id = int(request.vars.auth_user_id) if "auth_user_id" in request.vars.keys() else auth.user_id
    db.posts.posted_to.default = auth_user_id
    form = crud.create(db.posts)
    form.custom.widget["corpo"].update(_placeholder=T("Scrivi qualcosa..."))    
    user = db.auth_user(auth_user_id)
    if auth_user_id==auth.user_id:
        profile_form = auth.profile()
        pwd_form = auth.change_password()
    else:
        db.auth_user.picture.readable = False
        db.auth_user.thumbnail.readable = False
        profile_form = crud.read(db.auth_user, user)
        pwd_form = None
    user_friends = [auth_user_id]+getUserFriends(auth_user_id)
    if not user or not (auth_user_id==auth.user_id or auth_user_id in user_friends):
        redirect(URL('index'))
    posts = db(db.posts.posted_to==auth_user_id).select(orderby=~db.posts.data_ora,
                                                        limitby=(0, 100))
    return locals()

@auth.requires_login()
def search():
    form = SQLFORM.factory(Field('nome', requires=IS_NOT_EMPTY(), label=T("Nome")))
    if form.accepts(request):
        tokens = form.vars.nome.split()
        query = reduce(lambda a,b:a&b,
                       [db.auth_user.first_name.contains(k)|db.auth_user.last_name.contains(k) for k in tokens])
        users = db(query).select(orderby=db.auth_user.first_name|db.auth_user.last_name)
    else:
        users = []
    return locals()

@auth.requires_login()
def friends():
    friends = db(db.auth_user.id==db.amicizie.mittente_id)(db.amicizie.destinatario_id==auth.user_id).select(orderby=db.auth_user.first_name|db.auth_user.last_name)
    requests = db(db.auth_user.id==db.amicizie.destinatario_id)(db.amicizie.mittente_id==auth.user_id).select(orderby=db.auth_user.first_name|db.auth_user.last_name)
    return locals()

@auth.requires_login()
def friendship():
    try:
        a0, a1 = request.args(0), request.args(1)
        if request.env.request_method!='POST':
            raise HTTP(400)
        if a0=='request' and not db.amicizie(mittente_id=auth.user_id, destinatario_id=a1):
            db.amicizie.insert(mittente_id=auth.user_id, destinatario_id=a1)
        elif a0=='accept':
            db(db.amicizie.destinatario_id==auth.user_id)(db.amicizie.mittente_id==a1).update(is_accettata=True)
        elif a0=='deny':
            db(db.amicizie.destinatario_id==auth.user_id)(db.amicizie.mittente_id==a1).delete()
        elif a0=='remove':
            db(db.amicizie.mittente_id==auth.user_id)(db.amicizie.destinatario_id==a1).delete()
    except Exception, e:
        print e

@auth.requires_login()
def likePost():
    post_id = int(request.vars.post_id)
    if not db.post_likes(post_id=post_id, auth_user_id=auth.user_id):
        db.post_likes.insert(post_id=post_id, auth_user_id=auth.user_id)

@auth.requires_login()
def commentPost():
    post_id = int(request.vars.post_id)
    commento = request.vars.commento
    db.post_comments.insert(post_id=post_id, auth_user_id=auth.user_id, corpo=commento)
    return_html = '<div class="media stream">'\
                    '<a class="media-avatar small pull-left" href="%s">' \
                        '<img src="%s">' \
                    '</a>'\
                    '<div class="media-body">'\
                     '<div class="stream-headline">'\
                        '<h5 class="stream-author">'\
                            '<a href="%s">%s</a><small>%s:</small>'\
                        '</h5>'\
                        '<div class="stream-text">'\
                            '%s'\
                        '</div>'\
                    '</div>'\
                    '</div>'\
                '</div>'%(URL('wall', vars={'auth_user_id':auth.user_id}),
                          URL('default', 'download', args=db.auth_user(auth.user_id).thumbnail),
                          URL('wall', vars={'auth_user_id':auth.user_id}),
                          name_of(db.auth_user(auth.user_id)),
                          datetime.datetime.now(),
                          XML(commento))    
    return XML(return_html)

@auth.requires_login()
def logout():
    auth.logout()
    redirect(URL('index'))
        
    